package hy.service.impl;

import hy.bean.User;
import hy.dao.UserDao;
import hy.service.UserService;
import hy.util.PassUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional(propagation= Propagation.REQUIRED,rollbackFor=Exception.class)
public class UserServiceImpl implements UserService {
    @Autowired
	UserDao userDao;

	public void regist(User u) {
		//使用盐值
		String salt = PassUtil.randomSalt();
		u.setPass(PassUtil.encode(u.getPass(), salt));
		u.setSalt(salt);
		
		userDao.insert(u);
	}
	//登录不再由dao实现，交给shiro实现
	public String login(User user) {		
		UsernamePasswordToken tok = new UsernamePasswordToken(user.getName(),user.getPass());
		//默认是从cookie中读取sessionId以此来维持会话。如果在分布式集群环境中可以把session放在redis管理，可以实现session共享，可自定义sessionManager，重写getSessionId方法。
		Subject sub = SecurityUtils.getSubject();
		String err=null;
		try{
		////调用realm中的doGetAuthen,如果是sub.hasRole("manager")则会调用realm中的doGetAuthor
			sub.login(tok);		
		}catch (AuthenticationException e) {
			err = "用户名或密码错误";
		}
		return err;
	}
}